package com.wash.shoes.controller.mobile;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.domain.dto.ShopStsXcxDto;
import com.wash.shoes.domain.vo.DisStsTotalVo;
import com.wash.shoes.domain.vo.OrderDetailVo;
import com.wash.shoes.domain.vo.StsOrderVo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.RegionDistributorPo;
import com.wash.shoes.entity.RegionTransactionDetailPo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.service.*;
import com.wash.shoes.util.DateUtils;
import com.wash.shoes.util.StsDateInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author ljg
 * @since 2024-10-11
 */
@Log4j2
@Api(tags = {"分销-分销统计"})
@RestController
@RequestMapping("/mobile-api/regionTransactionDetail")
public class RegionTransactionDetailMController {

    @Resource
    RegionTransactionDetailService regionTransactionDetailService;

    @Resource
    OrderService orderService;

    @Resource
    RegionCustomerService regionCustomerService;

    @Resource
    RegionDistributorService regionDistributorService;

    @PostMapping("/recommendPageList")
    @ApiOperation("推广的订单")
    public R<Page<OrderDetailVo>> recommendPageList(@RequestBody ShopStsXcxDto shopStsXcxDto) {
        log.info("recommendPageList param is {}", JSONObject.toJSONString(shopStsXcxDto));
        StsDateInfoUtil.processDate(shopStsXcxDto);
        Page<OrderDetailVo> page = orderService.recommendPageList(shopStsXcxDto);
        return R.ok(page);
    }

    @PostMapping("/recommendIncome")
    @ApiOperation("推广的收益")
    public R<List<StsOrderVo>> recommendIncome(@RequestBody ShopStsXcxDto shopStsXcxDto) {
        log.info("recommendIncome param is {}", JSONObject.toJSONString(shopStsXcxDto));
        StsDateInfoUtil.processDate(shopStsXcxDto);
        // 推广的收益 应该统计有效的收益
        List<StsOrderVo> dataList = regionTransactionDetailService.recommendDayIncome(shopStsXcxDto);
        return R.ok(dataList);
    }

    @PostMapping("/recommendUser")
    @ApiOperation("推广的用户数量")
    public R<List<StsOrderVo>> recommendUser(@RequestBody ShopStsXcxDto shopStsXcxDto) {
        log.info("recommendUser param is {}", JSONObject.toJSONString(shopStsXcxDto));
        StsDateInfoUtil.processDate(shopStsXcxDto);
        // 推广的收益 应该统计有效的收益
        List<StsOrderVo> dataList = regionCustomerService.recommendDayUser(shopStsXcxDto);
        return R.ok(dataList);
    }

    @PostMapping("/stsTotal")
    @ApiOperation("总的统计数量")
    public R<DisStsTotalVo> stsTotal(@RequestBody ShopStsXcxDto shopStsXcxDto) {
        log.info("stsTotal param is {}", JSONObject.toJSONString(shopStsXcxDto));
        // 推广的收益 应该统计有效的收益
        DisStsTotalVo vo = new DisStsTotalVo();
        RegionDistributorPo po = regionDistributorService.getByUserId(shopStsXcxDto.getUserId());
        if (po == null) {
            return R.ok(vo);
        }

        StsOrderVo dataInfo = regionTransactionDetailService.stsOrderInfo(shopStsXcxDto, 1, "1");
        if (dataInfo == null) {
            dataInfo = new StsOrderVo();
            dataInfo.setOrderPrice(0D);
            dataInfo.setTotalPrice(0D);
        }
        vo.setOrderTotal(dataInfo.getTotalPrice());
        vo.setIncomeTotal(dataInfo.getOrderPrice());
        StsOrderVo dataInfo2 = regionTransactionDetailService.stsOrderInfo(shopStsXcxDto, 0, "1");
        if (dataInfo2 == null) {
            dataInfo2 = new StsOrderVo();
            dataInfo2.setOrderPrice(0D);
            dataInfo2.setTotalPrice(0D);
        }
        vo.setPendingAmount(dataInfo2.getOrderPrice());
        vo.setWithDrawableAmount(po.getPromotionProfit());
        vo.setTotalUser(po.getPromotionNum());
        return R.ok(vo);
    }

    @PostMapping("/incomeExpenseList")
    @ApiOperation("收支列表")
    public R<Page<RegionTransactionDetailPo>> incomeExpenseList(@RequestBody ShopStsXcxDto shopStsXcxDto) {
        log.info("incomeExpenseList param is {}", JSONObject.toJSONString(shopStsXcxDto));
        StsDateInfoUtil.processDate(shopStsXcxDto);
        Page<RegionTransactionDetailPo> page = regionTransactionDetailService.incomeExpenseList(shopStsXcxDto);
        return R.ok(page);
    }

    @GetMapping("/userWithdrawalRequest")
    @ApiOperation("用户提现")
    public R<RegionTransactionDetailPo> userWithdrawalRequest(String userId, Double amount) {
        log.info("userWithdrawalRequest param is {} {}", userId, amount);
        // 查询用户提现中的订单
        RegionTransactionDetailPo detailPo = regionTransactionDetailService.getUserOutProcess(userId);
        if (detailPo != null) {
            throw new WashException("有处理中的提现,请等待完成");
        }

        //同一个用户一个星期只能提一次现：暂时不限制，因为没有提现状态标识
        List<RegionTransactionDetailPo> transactionDetailPoList = regionTransactionDetailService.getUserOutProcessByStatusAndUserId(userId);
        RegionTransactionDetailPo regionTransactionDetailPo = Optional.ofNullable(transactionDetailPoList).orElse(Lists.newArrayList()).stream().findFirst().orElse(null);
        if (!Objects.isNull(regionTransactionDetailPo)) {
            boolean than7Days = DateUtils.isCreatedTimeGreaterThan7Days(regionTransactionDetailPo);
            if(!than7Days) {
                throw new WashException("一个星期之内只能提现一次!");
            }
        }

        // 是不是超出限制
        RegionDistributorPo po = regionDistributorService.getByUserId(userId);
        if (po == null || po.getStatus() == 0) {
            throw new WashException("你不能提现,请联系管理员");
        }
        // 超出限制
        if (po.getPromotionProfit() - amount < 0) {
            throw new WashException("提现超出限制");
        }
        detailPo = new RegionTransactionDetailPo();
        detailPo.setRecommendId(userId);
        detailPo.setType("2");
        detailPo.setShareRatio(100.0);
        detailPo.setTotalPrice(amount);
        detailPo.setPromotionProfit(amount);
        detailPo.setStatus(0);
        regionTransactionDetailService.save(detailPo);

        return R.ok(detailPo);
    }
}

